package com.thingsgrid.device.base;

import com.thingsgrid.device.entity.Device;
import com.thingsgrid.device.entity.DeviceMaintenanceRecord;
import com.thingsgrid.device.mapper.DeviceMapper;
import com.thingsgrid.device.service.IShadowService;
import com.thingsgrid.device.utils.JsonTransform;
import com.thingsgrid.device.utils.TimeUtils;
import com.thingsgrid.mqtthelper.feign.MqttHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.UUID;

/**
 * 功能说明：设备抽象类
 *
 * @author 李龙飞
 * @since 2019/9/18 14:53
 */
@Slf4j
public abstract class AbstractDevice extends AbstractProduct{

	@Autowired
	private IShadowService shadowService;
	@Autowired
	private MqttHelper mqttHelper;
	@Autowired
	private DeviceMapper deviceMapper;

	/**
	 *说明：设备开关机
	 *@author lilongfei
	 *@since 2019/9/18 15:06
	 */
	protected boolean controlDevice(String deviceId,String userId,String control){
		String controlStr;
		//查询设备当前开关机状态
		String openState = deviceMapper.getDeviceInfoById(deviceId).getDeviceShadow().getState().get("reported").get("online").toString();
		int updateDesired = shadowService.insertDeviceDesired(deviceId,"online",control);
		if(openState.equals(control)){
			return true;
		}else if(updateDesired==0){
			log.error("设备维护异常");
			return false;
		}else{
			String sendContent = JsonTransform.deviceControlJsonTransform("","200","","","");
			mqttHelper.sendMsg("/IotMan_Co/action/request/"+deviceId+"/device_control",sendContent);
			//插入操作记录
			if(control.equals("ON")){
				controlStr="开机";
			}else{
				controlStr="关机";
			}
			deviceMapper.insertDeviceMaintenanceRecord(new DeviceMaintenanceRecord(UUID.randomUUID().toString(),
				controlStr,deviceId,userId, TimeUtils.stampToDate(String.valueOf(System.currentTimeMillis())),deviceMapper.getDeviceInfoById(deviceId).getProductId()));
			return true;
		}
	}

	/**
	 *说明：根据ID获取设备信息
	 *@author lilongfei
	 *@since 2019/9/18 16:56
	 */
	protected Device getDeviceInfoById(String deviceId){
		return deviceMapper.getDeviceInfoById(deviceId);
	}


}
